<?php
/**
 * 用户模块类
 */
class MiniprogramModel extends BpfServiceModel
{
  private $_appid = '';
  private $_secret = '';

  public function __init()
  {
    $configModel = $this->getModel('config');
    $this->_appid = $configModel->get('appid');
    $this->_secret = $configModel->get('appsecret');
  }

  public function getAccesstoken()
  {
    $cacheid = 'accesstoken' . $this->_appid;
    $redisModel = $this->getModel('redis');
    if ($accesstoken = $redisModel->__call('get', [$cacheid])) {
      return $accesstoken;
    }
    $data = json_decode($this->get('https://api.weixin.qq.com/cgi-bin/token', [
      'grant_type' => 'client_credential',
      'appid' => $this->_appid,
      'secret' => $this->_secret
    ]));
    if ($accesstoken = $data->access_token ?? false) {
      $redisModel->__call('set', [$cacheid, $accesstoken, 7200]);
    }
    return $accesstoken;
  }

  public function jscode2session($code)
  {
    return json_decode($this->get('https://api.weixin.qq.com/sns/jscode2session?' . http_build_query([
      'appid' => $this->_appid,
      'secret' => $this->_secret,
      'js_code' => $code,
      'grant_type' => 'authorization_code'
    ])));
  }

  public function sendTemplate($to, $template, $formid, $data, $page = '')
  {
    return $this->post('https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?' . http_build_query([
      'access_token' => $this->getAccesstoken()
    ]), urldecode(json_encode([
      'touser' => $to,
      'template_id' => $template,
      'form_id' => $formid,
      'page' => $page,
      'data'=> $data
    ])), [], false);
  }

  public function getWxaCodeunLimit($page, $scene, $width = 430, $is_hyaline = true)
  {
    return $this->post('https://api.weixin.qq.com/wxa/getwxacodeunlimit?' . http_build_query([
      'access_token' => $this->getAccesstoken()
    ]), urldecode(json_encode([
      'scene' => $scene,
      'page' => $page,
      'width' => 100,
      'is_hyaline' => $is_hyaline
    ])), [], false);
  }

}
